<?php

define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);
require ROOT_PATH . 'vendor/autoload.php';

use Slim\Factory\AppFactory;

// 载入配置信息
require_once ROOT_PATH . 'bootstrap/config.php';
date_default_timezone_set($_ENV['app_timezone']);

// APP 实例
$app = AppFactory::create();
$errorHandler = new App\Exceptions\HttpErrorHandler(
    $app->getCallableResolver(),
    $app->getResponseFactory(),
    App\Components\Providers::logger('app')
);
$serverRequestCreator = Slim\Factory\ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
$shutdownHandler = new App\Exceptions\ShutdownHandler($request, $errorHandler, $_ENV['app_debug'] ?? true);
register_shutdown_function($shutdownHandler);
$app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware($_ENV['app_debug'] ?? true, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);
unset($errorHandler, $serverRequestCreator, $request, $shutdownHandler, $errorMiddleware);

// 定义DB门面
Illuminate\Support\Facades\DB::setFacadeApplication([
    'db' => App\Components\Providers::database()->getDatabaseManager(),
    'date' => new Carbon\Factory(['timezone' => $_ENV['app_timezone']]),
]);
// 注册LOG全局变量
Monolog\Registry::addLogger(App\Components\Providers::logger('app'), 'app');

// 通用中间件
$app->add(new App\Middleware\TrimStringsParameterProcessing());
$app->add(new App\Middleware\QuestionMarkParameterProcessing());

// 路由定义
$routes = require ROOT_PATH . 'bootstrap/routes.php';
$routes($app);
unset($routes);

$app->run();
